package com.xneure.utils;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class ImgUtil {
	/**
	 * 生成二维码(QRCode)图片的公共方法
	 * 
	 * @param content
	 *            存储内容
	 * @return
	 */
	public static BufferedImage watermark;

	public static BufferedImage qRCode(String contents, int size) {
		try {
			final int BLACK = 0xff000000;
			final int WHITE = 0xFFFFFFFF;
			contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
			QRCodeWriter writer = new QRCodeWriter();
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.MARGIN, "1");
			BitMatrix matrix = writer.encode(contents, BarcodeFormat.QR_CODE, size, size, hints);
			BufferedImage image = new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_ARGB);
			for (int x = 0; x < size; x++) {
				for (int y = 0; y < size; y++) {
					image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
				}
			}
			if (null != watermark) {
				int logoSize = (size) / 2 - watermark.getWidth() / 2;
				watermark(image, watermark, logoSize, logoSize, 1f);
			}
			return image;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static BufferedImage watermark(BufferedImage srcImg, BufferedImage logoImg, int x, int y, float alpha)
			throws IOException {
		// 获取层图
		// 创建Graphics2D对象，用在底图对象上绘图
		Graphics2D g2d = srcImg.createGraphics();
		int waterImgWidth = logoImg.getWidth();// 获取层图的宽度
		int waterImgHeight = logoImg.getHeight();// 获取层图的高度
		// 在图形和图像中实现混合和透明效果
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
		// 绘制
		g2d.drawImage(logoImg, x, y, waterImgWidth, waterImgHeight, null);
		g2d.dispose();// 释放图形上下文使用的系统资源
		return srcImg;
	}

	public static void qRCode(OutputStream os, String contents, int size) {
		try {
			ImageIO.write(qRCode(contents, size), "png", os);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void save(FileOutputStream outImgStream,BufferedImage bufImg) throws IOException{
		ImageIO.write(bufImg,"jpg",outImgStream);
	}
}
